package com.allwees.eladmin.bs.service.impl;

import com.google.common.collect.Sets;
import com.allwees.bs.core.model.user.bo.MerchantDeptCreateBo;
import com.allwees.eladmin.bs.service.BranchUserService;
import lombok.extern.slf4j.Slf4j;
import me.zhengjie.modules.system.domain.Dept;
import me.zhengjie.modules.system.domain.Job;
import me.zhengjie.modules.system.domain.Role;
import me.zhengjie.modules.system.domain.User;
import me.zhengjie.modules.system.repository.JobRepository;
import me.zhengjie.modules.system.repository.RoleRepository;
import me.zhengjie.modules.system.service.DeptService;
import me.zhengjie.modules.system.service.UserService;
import me.zhengjie.modules.system.service.dto.UserDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author mouhaining
 * @date 2019-12-20
 */
@Slf4j
@Service
public class BranchUserServiceImpl implements BranchUserService {

    @Autowired
    private DeptService deptService;

    @Autowired
    private UserService userService;

    @Autowired
    private JobRepository jobRepository;

    @Autowired
    private RoleRepository roleRepository;

    @Override
    @Transactional
    public UserDto createMerchantUser(MerchantDeptCreateBo createBo) {
        Dept dept = new Dept();
        dept.setEnabled(true);
        dept.setName(createBo.getDeptName());
        dept.setPid(createBo.getPid());
        deptService.create(dept);

        User user = new User();
        user.setBranchUuid(createBo.getBranchUuid());
        user.setEnabled(true);
        user.setUsername(createBo.getPhone());
        user.setNickName(createBo.getNickname());
        user.setPassword(createBo.getPassword());
        user.setPhone(createBo.getPhone());
        user.setEmail(createBo.getEmail());
        user.setBranchType(createBo.getBranchType());

        Job job = new Job();
        job.setName(createBo.getDeptName() + "管理员");
        job.setDept(dept);
        job.setEnabled(true);
        job.setSort(1L);
        job = jobRepository.save(job);
//
//        String roleName = BooleanOptional.rule(DEFAULT_SUPPLIER_ROLE_NAME, DEFAULT_RETAILER_ROLE_NAME)
//                .get(EBranchType.SUPPLIER.equals(createBo.getBranchType()));

        Role role = roleRepository.findByName(createBo.getBranchType().name());

        if (role != null) {
            user.setRoles(Sets.newHashSet(role));
        }

        user.setJob(job);
        user.setDept(dept);
        return userService.create(user);
    }
}
